<?php

namespace app\common\model\coupon;

use think\Model;


class Log extends Model
{

    // 表名
    protected $name = 'coupon_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'state_text'
    ];



    public function getTypeList()
    {
        return ['0' => __('Type 0'), '1' => __('Type 1')];
    }

    public function getStateList()
    {
        return ['0' => __('State 0'), '1' => __('State 1'), '2' => __('State 2')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function editState($user_id)
    {
        return  self::where('user_id', $user_id)->where('enddate', '<', date('Y-m-d'))->where('state', 1)->update(['state' => 0]) ? true : false;
    }
    //  下单默认使用最大面值优惠券
    public static function useMaxCoupon($money, $user_id)
    {
        return self::where('money', '<', $money)->where('user_id', $user_id)->where('state', 1)->where('startdate', '<', date('Y-m-d'))->where('enddate', '>', date('Y-m-d'))->order('price desc')->find();
    }
    //  检查优惠券是否能使用
    public static function useCoupon($money, $coupon_id, $user_id)
    {
        $coupon = self::get(['id' => $coupon_id, 'user_id' => $user_id]);

        if ($coupon['state'] == 0) {
            return exception('优惠券已过期');
        }
        if ($coupon['state'] == 2) {
            return exception('优惠券已使用');
        }

        if ($money <= $coupon['money']) {
            return exception('优惠券最低使用金额￥' . $coupon['money']);
        }
        if (date('Y-m-d') < $coupon['startdate']) {
            return exception('有效开始日期：' . $coupon['startdate']);
        }
        if (date('Y-m-d') > $coupon['enddate']) {
            return exception('有效截止日期：' . $coupon['enddate']);
        }
        if ($money > $coupon['price']) {
            return $coupon['price'];
        } else {
            return $money;
        }
    }
}
